var express = require("express");
var router = express.Router();
//引入mongoose
let mongoose = require("mongoose");

//登录
router.post("/myLogin", async function (req, res) {
  // let { acc, pwd } = req.params; // params传参
  let { username, password } = req.body; // body传参

  console.log(req.body);
  //根据账号查询用户数据
  let re = await mongoose.model("userModel").find({
    name: username,
  });
  // console.log(re);
  if (re.length < 1) {
    res.send({
      code: 400,
      message: "账号不存在!请先注册!",
    });
  } else {
    if (re[0].pwd == password) {
      res.send({
        code: 200,
        message: "登录成功!",
      });
    } else {
      res.send({
        code: 250,
        message: "密码错误!",
      });
    }
  }
});

// 注册
router.post("/myRegister", async function (request, result) {
  const { username, password } = request.body;
  let res = await mongoose.model("userModel").find({
    name: username,
  });
  if (res.length > 0) {
    result.send({
      code: 400,
      message: "账号已存在",
    });
  } else {
    mongoose
      .model("userModel")({ name: username, pwd: password })
      .save()
      .then((response) => {
        if (JSON.stringify(response) !== "{}") {
          result.send({
            success: true,
            message: "注册成功",
          });
        } else {
          result.send({
            success: false,
            message: "注册失败",
          });
        }
      });
  }
});

// 修改密码
router.post("/modifyPwd", async function (request, result) {
  const { username, password, repeatPassword } = request.body;
  let res = await mongoose
    .model("userModel")
    .updateOne({ name: username, pwd: password }, { pwd: repeatPassword });
  if (JSON.stringify(res) !== "{}" && res.modifiedCount == 1) {
    result.send({
      code: 200,
      message: "修改成功",
    });
  } else {
    result.send({
      code: 400,
      message: "账号或密码不正确",
    });
  }
  console.log("re", res);
});

module.exports = router;
